package zhtt.ehcache.repository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;
import zhtt.ehcache.domain.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ztt on 2018/4/29.
 */
@Repository
public class UserRepositoryImpl implements UserRepository {

    private JdbcTemplate jdbcTemplate;

    @Autowired
    public UserRepositoryImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public long count() {
        return jdbcTemplate.queryForLong("select count(id) from zhtt_cache_user");
    }

    @Override
    public User findOne(int id) {
        return jdbcTemplate.queryForObject(
                SELECT_USER + " where id=?", new UserRowMapper(), id);
    }

    @Override
    public User save(User user) {
        Integer id=user.getId();
        if(id == null){
            int spitterId = insertSpitterAndReturnId(user);
            return new User(spitterId, user.getName(),user.getAge());
        } else {
            jdbcTemplate.update("update zhtt_cache_user set name=?, age=? where id=?",
                    user.getName(),
                    user.getAge(),
                    id);
        }
        return null;
    }

    @Override
    public User findByName(User user) {
        return null;
    }

    @Override
    public void delete(int id) {

    }

    @Override
    public List<User> findAll() {
        return null;
    }

    private static final String SELECT_USER = "select id, name, age from zhtt_cache_user";

    private static final String INSERT_USER = "insert into zhtt_cache_user (name, age) values (?, ?)";

    private static final class UserRowMapper implements RowMapper<User> {
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            int age = rs.getInt("age");
            return new User(id, name, age);
        }
    }

    @SuppressWarnings("unused")
    private void insertUser(User user) {
        jdbcTemplate.update(INSERT_USER,
                user.getName(),
                user.getAge());
    }

    private int insertSpitterAndReturnId(User user) {
        SimpleJdbcInsert jdbcInsert = new SimpleJdbcInsert(jdbcTemplate).withTableName("zhtt_cache_user");
        jdbcInsert.setGeneratedKeyName("id");
        Map<String, Object> args = new HashMap<String, Object>();
        args.put("name", user.getName());
        args.put("age", user.getAge());
        int spitterId = jdbcInsert.executeAndReturnKey(args).intValue();
        return spitterId;
    }
}
